package com.thinkgem.jeesite.modules.unfee.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.building.entity.Room;
import com.thinkgem.jeesite.modules.building.service.RoomService;
import com.thinkgem.jeesite.modules.record.entity.Record;
import com.thinkgem.jeesite.modules.record.service.RecordService;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.unfee.entity.Unfee;
import com.thinkgem.jeesite.modules.unfee.service.UnfeeService;

@Controller
@RequestMapping(value="${adminPath}/unfee")
public class UnfeeController extends BaseController{

	@Autowired
	UnfeeService unfeeservice;
	@Autowired
	SystemService systemservice;
	@Autowired
	RecordService recordservice;
	@Autowired
	RoomService roomservice;
	@RequestMapping(value="/unfeeList")
	public String unfeeList(HttpServletResponse response,HttpServletRequest request,Model model){
		Page<Unfee> page = unfeeservice.findPage(new Page<Unfee>(request, response),new Unfee());
		model.addAttribute("page", page);
		return "modules/fee/unfeeList";
		
	}
	@RequestMapping(value="deleteUnFee")
	public String deleteUnfee(@RequestParam("id")String id,Model model){
		Date now  = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Unfee unfee = unfeeservice.get(id);
		User user = systemservice.getUser(unfee.getUser().getId());
		Room room = roomservice.findRoomByOwnerId(unfee.getUser().getId());
		if(Double.parseDouble(user.getBalance())  >= Double.parseDouble(unfee.getPrice()) )
		{
			user.setBalance(Double.parseDouble(user.getBalance())  - Double.parseDouble(unfee.getPrice())+"");
			systemservice.saveUser(user);//扣除费用，再删除单子
			unfeeservice.deleteUnFee(unfee);
			Record record = new Record();
			record.setId(UUID.randomUUID().toString());
			record.setCreateTime(format.format(now).toString());
			record.setMoney(unfee.getPrice());
			record.setUser(UserUtils.getUser());
			record.setRoom(room);
			recordservice.insertRecord(record);
		}
		return "redirect:"+Global.getAdminPath()+"/unfee/unfeeList";
	}
}

